<template>
  <div class="wrap">
    <div class="head">
      <span @click="backPath()" style="cursor: pointer;"><i class="el-icon-arrow-left"></i>返回</span>
      <span class="primary">积分兑换</span>
    </div>
    <div class="mian">
      <el-form :model="params" ref="ruleForm" label-width="140px" size="small">
        <el-form-item label="兑换设置" required style="margin-bottom: 0">
          <el-row type="flex" v-for="(item,index) in params.redEnvelopeAttach" :key="index">
            <el-form-item :prop="'redEnvelopeAttach.' + index + '.integral'" :rules="[{ required: true, message: '请输入积分数量' }]">
              <el-input-number :min='1' :max='99999' :precision='0' v-model="item.integral" />
            </el-form-item>
            <span style="margin:0 5px">积分</span>
            <el-form-item :prop="'redEnvelopeAttach.' + index + '.redamount'" :rules="[{ required: true, message: '请输入金额'}]">
              <el-input-number v-model="item.redamount" :min='0.1' :max='99' :precision='1' />
            </el-form-item>
            <span style="margin-left: 5px">元通用红包</span>
            <el-form-item style="margin-left: 50px">
              <el-button class="el-text-success" type="text" v-if="params.redEnvelopeAttach.length < 5 && index === 0" @click="addFast()">
                <i class="el-icon-circle-plus-outline"></i>添加({{params.redEnvelopeAttach.length}}/5)
              </el-button>
              <el-button class="el-text-success" type="text" v-if="index > 0" @click="lessFast(index)">删除</el-button>
            </el-form-item>
           </el-row>
        </el-form-item>
        <el-form-item label="使用条件" required style="margin-bottom: 0">
          <el-form-item prop="fulls" :rules="[{ required: true, message: '请输入金额' }]">
            消费满 <el-input-number :min='0' :max='999' :precision='0' v-model="params.fulls" /> 元可用
          </el-form-item>
        </el-form-item>
        <el-form-item label="红包有效期" required style="margin-bottom: 0">
          <el-form-item prop="redvalidday" :rules="[{ required: true, message: '请输入金额' }]">
            <el-input-number :min='1' :max='999' :precision='0' v-model="params.redvalidday" /> 天
          </el-form-item>
        </el-form-item>
        <el-form-item label="开启分区域" v-if="childrenAgentId.length > 0">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="params.agentids" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="item in childrenAgentId" :label="item.id" :key="item.id">{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <div class="msg">
          <p class="head">说明:</p>
          <p class="item">1.用户每消费一元会产生一个积分。</p>
          <p class="item">2.活动开启后，用户可以用积分兑换相应设置的红包。</p>
          <p class="item">3.该红包支持{{childrenAgentId.length ? '开启区域' : '全平台'}}，全类目使用（跑腿订单除外）。</p>
        </div>
        <el-form-item>
          <el-button @click="backPath()">取消</el-button>
          <el-button type="primary" plain @click="submitForm('ruleForm', 0)" :loading="isloadingUpdate">仅保存</el-button>
          <el-button type="primary" @click="submitForm('ruleForm', 1)" :loading="isloadingUpdate">保存并开启</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { redEnvelopeSave, redEnvelopeUpload, redEnvelopeInfo } from '@/api/activity'
import { agentSubList } from '@/api/com'
export default {
  data() {
    return {
      params: {
        type: 3,
        redEnvelopeAttach: [{ integral: undefined, redamount: undefined}],
        redvalidday: undefined,
        fulls: undefined,
        agentids: []
      },
      checkAll: false,
      isIndeterminate: false,
      childrenAgentId: [],
      isloadingUpdate: false
    }
  },
  methods: {
    backPath() {
      this.$router.back()
    },
    addFast() {
      this.params.redEnvelopeAttach.push({ integral: undefined, redamount: undefined})
    },
    lessFast(index) {
      this.params.redEnvelopeAttach.splice(index, 1)
    },
    handleCheckAllChange(val) {
      this.params.agentids = val ? this.childrenAgentId.map(i => i.id) : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.childrenAgentId.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.childrenAgentId.length
    },
    getDetail(id, agentid) { // 获取活动详情
      const params = { id, agentid }
      redEnvelopeInfo(params).then(res => {
        if (res.success) {
          const redEnvelopeAttach = res.data.redEnvelopeAttach.map(i => {
            return {
              integral: i.integral || undefined, 
              redamount: i.redamount || undefined,
              id: i.id, redid: i.redid
            }
          })
          this.params = {
            type: 3,
            agentids: res.data.agentids ? res.data.agentids.split(',').map(i => parseInt(i)) : [],
            redEnvelopeAttach: redEnvelopeAttach,
            redvalidday: res.data.redvalidday || undefined,
            fulls: res.data.fulls || undefined
          }
          this.handleCheckedCitiesChange(this.params.agentids)
        }
      })
    },
    submitForm(formName, type) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.isloadingUpdate = true
          const params = { ...this.params, agentid: this.query.agentid, enable: type }
          params.agentids = params.agentids.length ? params.agentids.join(',') : null
          if (this.query.id) {
            params.id = this.query.id
            redEnvelopeUpload(params).then(res => {
              if (res.success) {
                this.backPath()
              }
            }).finally(() => { this.isloadingUpdate = false })
          } else {
           redEnvelopeSave(params).then(res => {
              if (res.success) {
                this.backPath()
              }
            }).finally(() => { this.isloadingUpdate = false })
          }
        } else {
          return false
        }
      })
    },
    getAgentSubList(agentId) { // 获取子区域
      agentSubList({ agentId }).then(res => {
        if (res.success) {
          this.childrenAgentId = res.data.children || []
        }
      })
    }
  },
  mounted() {
    this.query = this.$route.query
    if (this.query.agentid) {
       this.getAgentSubList(this.query.agentid)
      if (this.query.id) {
        this.getDetail(this.query.id, this.query.agentid)
      }
    } else {
      this.$router.back()
    }
  }
}
</script>
<style lang="scss" scoped>
  .wrap {
    .head{
      height: 40px;
      line-height: 40px;
      .primary{
        margin-left: 20px;
        font-weight: 600;
      }
    }
    .mian{
      padding: 40px 0 0 0;
    }
    .msg{
      margin: 30px 0;
      padding: 10px;
      border: 1px solid #ccc;
      .head{
        font-size: 16px;
        font-weight: 600;
        line-height: 40px;
      }
      .item{
        text-indent: 2em;
        line-height: 30px;
        color: #999;
      }
    }
  }
</style>